<script>
import { deepClone } from "@/utils/public";
/**
 * 公共的el-table-column上的属性，如果config中设置了相同的属性会覆盖
 * 权重：commonColumnProps < 用户自定义公共columnProps < config中设置的属性
 * */
// 表格body区域类名
const ELTABLE_WRAPPER_CLASS = ".el-table__body-wrapper";
// 表头区域类名
const ElTABLE_HEADER_CLASS = ".el-table__header-wrapper";
const commonTableProps = {
  "border": true,
  "header-cell-style": {
    "textAlign": "center",
    "backgroundColor": "#B1C8F9",
    "border": "1px solid #ccc",
    "fontSize": "16px",
    "color": "#333"
  }
};
const commonColumnProps = {
  "show-overflow-tooltip": true
};
export default {
  name: "DexTable",
  props: {
    // 表格数据
    data: {
      type: Array,
      require: true
    },
    // 用户自定义公共的el-column-table的属性
    columnProps: {
      tyep: Object,
      default: () => ({})
    },
    // 是否展示序号
    showIndex: {
      type: Boolean,
      default: true
    },
    // 是否可选择
    canSelect: {
      type: Boolean,
      default: false
    },
    /**
     * 表格配置，包括表格的表头，属性，render属性
     * */
    config: {
      tyep: Array,
      default: () => ({})
    },
    // 是否有分页
    withPage: {
      type: Boolean,
      default: true
    },
    total: {
      type: Number,
      default: 0
    },
    pageConfig: {
      type: Object,
      default: () => ({ })
    },
    flex: { // 该属性添加后，表格会自适应高度，当页面其他元素高度改变，影响到table高度时，需要手动调用setFlex
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      pageNum: 1,
      pageSize: 10,
      maxHeight: ""
    };
  },
  methods: {
    renderTable() {
      return (
        <el-table
          class='J_sortableTable'
          ref='sortableTable'
          style='width: 100%'
          maxHeight={this.maxHeight ? this.maxHeight : null}
          data={this.data}
          attrs={Object.assign(deepClone(commonTableProps), deepClone(this.$attrs))}
          on={this.$listeners}
        >
          {this.canSelect ? (
            <el-table-column
              type='selection'
              width='60'
              align='center'
            ></el-table-column>
          ) : null}
          {this.showIndex ? (
            <el-table-column
              type='index'
              label='序号'
              width='60'
              align='center'
            ></el-table-column>
          ) : null}

          {this.config.map((props) => {
            return props.slot ? (
              <el-table-column
                attrs={Object.assign(
                  deepClone(commonColumnProps),
                  deepClone(this.columnProps),
                  props
                )}
                scopedSlots={{
                  default: this.$scopedSlots[props.slot]
                    ? (scope) => this.$scopedSlots[props.slot](scope)
                    : null
                }}
              ></el-table-column>
            ) : (
              <el-table-column
                key={props.prop}
                attrs={Object.assign(
                  deepClone(commonColumnProps),
                  deepClone(this.columnProps),
                  props
                )}
                scopedSlots={{
                  default: props.render ? (scope) => props.render(this.h, scope.row, props) : null
                }}
              ></el-table-column>
            );
          })}
        </el-table>
      );
    },
    renderPage() {
      return (
        <div style='display:flex;justify-content: flex-end;align-items: center;font-size:16px;margin-top:10px'>
          <div style='letter-spacing: 2px;margin-right:2px'>共{this.total}条数据,共{this.calcNum(this.total)}页</div>
          <el-pagination
            background={true}
            current-page={this.pageNum}
            page-size={this.pageSize}
            layout=' prev, pager, next'
            total={this.total}
            on-size-change={this.handleSizeChange}
            on-current-change={this.handleCurrentChange}
            attrs={this.pageConfig}
          ></el-pagination>
        </div>
      );
    },
    // 计算分页页数
    calcNum(val) {
      if (val < 10) {
        return 1;
      } else {
        return Math.ceil(val / 10);
      }
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.$emit("handleSizeChange", { pageSize, pageNum: this.pageNum });
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.$emit("handleCurrentChange", { pageSize: this.pageSize, pageNum });
    },
    calHeight(parentNode, table) {
      const parentNodeHeight = parentNode.getBoundingClientRect().height;
      let otherHeight = 0;
      [...parentNode.children].forEach(child => {
        if (child !== table && [...child.classList].indexOf("el-loading-mask") < 0) {
          otherHeight += child.getBoundingClientRect().height;
        }
      });
      return parentNodeHeight - otherHeight;
    },
    // 给el-table表格中的body区域设置最大高度
    setTableBodyMaxHeight(tableDom, maxHeight) {
      const bodyWrapDom = tableDom.querySelector(ELTABLE_WRAPPER_CLASS);
      const headerDom = tableDom.querySelector(ElTABLE_HEADER_CLASS);
      const headerDomHeight = headerDom.getBoundingClientRect().height;
      bodyWrapDom.style.maxHeight = maxHeight - headerDomHeight + "px";
    },
    setFlex() {
      try {
        const table = this.$refs.sortableTable.$el;
        const parentNode = table.parentNode;
        if (parentNode) {
          const maxHeight = this.calHeight(parentNode, table);
          this.maxHeight = maxHeight + "px";
          this.$nextTick(() => {
            this.setTableBodyMaxHeight(table, maxHeight);
          });
        }
      } catch (error) {
        console.log(error);
      }
    }
  },
  mounted() {
    if (this.flex) {
      this.setFlex();
    }
  },
  render(h) {
    this.h = h;
    if (this.withPage) {
      return (
        <div class={this.flex ? "flex-1" : ""}>
          {this.renderTable()}
          {this.renderPage()}
        </div>
      );
    } else {
      return (
        this.renderTable()
      );
    }
  }
};
</script>
<style lang="less" scoped>
.flex-1 {
  flex: 1;
  height: 100%;
}
.J_sortableTable {
  transition: max-height .3s;

}
</style>
